package org.beynet.docs.sync;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.log4j.Logger;

/**
 * xml root class used to store current resumable uploads
 * @author beynet
 *
 */
@XmlRootElement(name="status")
public class SyncStatus {
    
    public static synchronized SyncStatus make(String fileName) {
        File file = new File(fileName);
        SyncStatus result = null ;
        if (file.exists()) {
            try {
                result = (SyncStatus) un.unmarshal(file);
            } catch (JAXBException e) {
                logger.error("Error reading file :"+fileName);
            }
        }
        if (result==null) {
            result = new SyncStatus();
        }
        result.setFileName(fileName);
        instance = result ;
        return(result);
    }
    
    public static synchronized SyncStatus getInstance() {
        return(instance);
    }
    
    public synchronized void updateStatus(String uploadingFileName,URI uri,boolean completed) {
        CurrentUpload found = null ;
        for (CurrentUpload upload : uploads) {
            if (upload.getFilePath().equals(uploadingFileName)) {
                found = upload ;
                break;
            }
        }
        if (completed==true) {
            if (found!=null) uploads.remove(found);
        }
        else {
            if (found==null) {
                found = new CurrentUpload();
                found.setFilePath(uploadingFileName);
                uploads.add(found);
            }
            found.setURI(uri);
        }
        try {
            mar.marshal(this, new File(this.fileName));
        } catch (JAXBException e) {
            logger.error("Unable to marshal into file "+this.fileName);
        }
    }
    
    protected void setFileName(String fileName) {
        this.fileName = fileName ;
    }
    
    @XmlElement(name="upload")
    public List<CurrentUpload> getUploading() {
        return(uploads);
    }
    
    private List<CurrentUpload> uploads = new ArrayList<CurrentUpload>();
    private String fileName ;
    
    private static JAXBContext context;
    private static Unmarshaller un ;
    private static Marshaller mar ;
    private static SyncStatus instance = null ; 
    private static final Logger logger = Logger.getLogger(SyncStatus.class);
    static {
        try {
            context = JAXBContext.newInstance(SyncStatus.class);
            un = context.createUnmarshaller();
            mar=context.createMarshaller();
        } catch (JAXBException e) {
            throw new RuntimeException("Error creating jaxbcontext",e);
        }
    }
}
